package com.chis.shardingjdbc.config;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

public class TzRangeShardAlgorithm implements RangeShardingAlgorithm<Date> {
    private static SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMM");

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> shardingValue) {
        String tableName = shardingValue.getLogicTableName();
        Range<Date> shardingKey = shardingValue.getValueRange();
        Date startShardingKey = shardingKey.lowerEndpoint();
        Date endShardingKey = shardingKey.upperEndpoint();
        return getMonthBetween(startShardingKey,endShardingKey,tableName);
    }

    public static List<String> getMonthBetween(Date minDate, Date maxDate,String tableName) {
        ArrayList<String> result = new ArrayList<String>();
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        min.setTime(minDate);
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
        max.setTime(maxDate);
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
        Calendar curr = min;
        while (curr.before(max)) {
            result.add(tableName.concat("_").concat(dateformat.format(curr.getTime())));
            curr.add(Calendar.MONTH, 1);
        }
        return result;
    }

}
